<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="ISBN" prop="bookIsbn">
                <el-input
                        v-model="queryParams.bookIsbn"
                        placeholder="请输入ISBN"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['information:information:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['information:information:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['information:information:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['information:information:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="informationList" @selection-change="handleSelectionChange" class="table el-table--border">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="informationId" />
            <el-table-column label="ISBN" align="center" prop="bookIsbn" />
            <el-table-column label="简介" align="center">
                <template #default="scope">
                    <div class="text" link type="primary" @click="showPopover1(scope.row)">{{scope.row.information}}</div>
                </template>
            </el-table-column>
            <el-table-column label="封面" align="center" prop="picture">
<!--                <template  #default="scope">-->
<!--                    <img :src="scope.row.picture">-->
<!--                </template>-->
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['information:information:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['information:information:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <el-dialog :title="title1" v-model="showPopover" width="500px" class="centered-dialog" append-to-body>
            <div>
                {{ content }}
            </div>
        </el-dialog>
        <!-- 添加或修改information对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="informationRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="ISBN" prop="bookIsbn">
                    <el-input v-model="form.bookIsbn" placeholder="请输入ISBN" />
                </el-form-item>
                <el-form-item label="简介">
                    <el-input v-model="form.information" placeholder="请输入简介" type="textarea" :rows="8"/>
                </el-form-item>
                <el-form-item label="封面" prop="picture">
                    <el-input v-model="form.picture" placeholder="请输入封面地址" />
                </el-form-item>
<!--                <el-form-item>-->
<!--                    <div>-->
<!--                        <h3>这是你上传的图片：</h3>-->
<!--                        <img v-if="imageUrl!==''" :src="this.hostURL+imageUrl" style="width: 400px; height: 300px; margin-top: 10px">-->
<!--                        <span v-else>暂未收到图片</span>-->
<!--                    </div>-->
<!--                </el-form-item>-->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm()">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Information">
import {
    listInformation,
    getInformation,
    delInformation,
    addInformation,
    updateInformation,
} from "@/api/information/information";
import { ref, reactive, toRefs, computed } from 'vue';
import {VueCropper} from "vue-cropper";
import axios from "axios";
import { ElMessage, ElMessageBox } from 'element-plus'
import {addBook, updateBook} from "@/api/book/book.js";

const informationList = ref([]);
const expandedRows = ref({});
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title1 = ref("简介");
let content = ref("");
const visible = ref(false);
const { proxy } = getCurrentInstance();
const showPopover = ref(false);


//图片裁剪数据
const options = reactive({
    img: '',     // 裁剪图片的地址
    autoCrop: true,            // 是否默认生成截图框
    autoCropWidth: 200,        // 默认生成截图框宽度
    autoCropHeight: 200,       // 默认生成截图框高度
    fixedBox: true,            // 固定截图框大小 不允许改变
    outputType: "png",         // 默认生成截图为PNG格式
    filename: 'picture',        // 文件名称
    previews: {}               //预览数据
});

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookIsbn: null,
        information: null,
        picture: null
    },
    rules: {
        bookIsbn: [
            { required: true, message: "ISBN不能为空", trigger: "blur" }
        ],
        information: [
            { required: true, message: "简介不能为空", trigger: "blur" }
        ],
        picture: [
            { required: true, message: "封面不能为空", trigger: "blur" }
        ]
    },
});

const { queryParams, form, rules } = toRefs(data);

const getFullInformation = (row) => {
    // 这里应该是获取完整的简介信息的逻辑
    return row.information; // 假设 information 是完整的简介信息
};

function showPopover1(row) {
    content = row.information;
    console.info(content)
    showPopover.value = true;
}

function closePopover() {
    showPopover.value = false;
}

function handleSuccess(res, file) {
    this.imageUrl = URL.createObjectURL(file.raw);
}
function submitUpload() {
    this.$refs.upload.submit();
    this.fileList = [];
}
function picUpload(f) {
    let params = new FormData()
    //注意在这里一个坑f.file
    params.append("file", f.file);
    axios({
        method: 'post',
        //这里的id是我要改变用户的ID值
        url: '/setimg/'+this.form.bookIsbn,
        data: params,
        headers: {
            'content-type': 'multipart/form-data'
        }
    }).then(res => {
        console.log(resp);
        this.imageUrl = resp.obj;
    })
}

function handleAvatarSuccess(res, file) {
    this.imageUrl = URL.createObjectURL(file.raw);
}

function editCropper() {
    open.value = true;
}
function beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
    }
    if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
}
/** 查询information列表 */
function getList() {
    loading.value = true;
    listInformation(queryParams.value).then(response => {
        informationList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        informationId: null,
        bookIsbn: null,
        information: null,
        picture: null
    };
    proxy.resetForm("informationRef");
}

function submitForm() {
    proxy.$refs["informationRef"].validate(valid => {
        if (valid) {
            if (form.value.informationId != null) {
                updateInformation(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addInformation(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    // 在这里调用添加Information的API
                    addInformation({
                        bookIsbn: form.value.bookIsbn, // 假设Information中有一个字段是ISBN
                    }).then(() => {
                        proxy.$modal.msgSuccess("书籍信息添加成功");
                    }).catch(error => {
                        proxy.$modal.msgError("添加书籍信息失败：" + error.message);
                    });
                    open.value = false;
                    getList();
                });
            }
        }
    });
}


/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.informationId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加information";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _informationId = row.informationId || ids.value
    getInformation(_informationId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改information";
    });
}

function toggleDetails(row) {
    expandedRows.value[row.informationId] = !expandedRows.value[row.informationId];
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _informationIds = row.informationId || ids.value;
    proxy.$modal.confirm('是否确认删除information编号为"' + _informationIds + '"的数据项？').then(function() {
        return delInformation(_informationIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('information/information/export', {
        ...queryParams.value
    }, `information_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style lang='scss' scoped>
.text {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* 限制为3行 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: pre-wrap;
    word-wrap: break-word;
    color: #1c84c6;
    text-decoration: underline;
    cursor: pointer;
}
/* 设置弹窗居中样式 */
.centered-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed; /* 使用固定定位 */
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) !important; /* 使用transform偏移自身宽高的50%来精确居中 */
    z-index: 1000; /* 确保弹窗位于页面其他元素之上 */
}
</style>